<template>
  <div>
    <customDialog
      :title="title"
      :dialogVisible="dialogVisible"
      @close="closeDialog(ruleFormRef)"
      @confirm="confirmDialog(ruleFormRef)"
      width="900"
    >
      <div>
        <el-form
          ref="ruleFormRef"
          :model="formData"
          :rules="rules"
          label-width="110px"
          class="form_box"
        >
          <el-row>
            <el-col :span="14">
              <el-form-item label="每集价格" prop="unblockCoinAmount">
                <el-input
                  v-model="formData.unblockCoinAmount"
                  placeholder="请输入每集价格"
                  clearable
                />
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <span style="vertical-align: sub">&nbsp;(单位：金币)</span>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="14">
              <el-form-item
                label="付费卡点"
                prop="chargeEpisodeNo"
                class="item_episodeNo"
                style="margin-left: -18px"
              >
                <el-tooltip
                  effect="dark"
                  content="新进用户立即生效，已进用户需等一段时间"
                  placement="top"
                >
                  <el-icon
                    class="tooltip_color"
                    style="
                      margin: 0 10px 0 -10px;
                      font-size: 18px;
                      cursor: pointer;
                    "
                  >
                    <QuestionFilled />
                  </el-icon>
                </el-tooltip>
                <el-input
                  v-model="formData.chargeEpisodeNo"
                  placeholder="请输入付费卡点"
                  clearable
                />
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <span style="vertical-align: sub">
                &nbsp;({{ ` 从第${formData.chargeEpisodeNo}集开始收费` }})
              </span>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="14">
              <el-form-item label="充值模板">
                <el-select
                  v-model="formData.payTplId"
                  placeholder="请选择"
                  clearable
                  @change="changeTemplate"
                >
                  <el-option
                    v-for="(item, index) in optionEpisode"
                    :key="index"
                    :label="item.text"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="" class="template_box">
            <!-- <p class="grey" style="margin: 0 0 12px" v-if="!formData.payTplId">
              当前剧集已使用
              <strong>默认</strong> 充值模板，可以在小程序管理中配置默认充值模板
            </p>
            <p class="grey" style="margin: 0 0 12px" v-else>
              当前剧集已使用 <strong>自定义</strong> 充值模板，点击
              <span class="operationClick" @click="getDefaultTemplate()"
                >恢复默认</span
              >
            </p> -->
            <!-- 模板 -->
            <defaultTemplate ref="baseTemplateRef" />
          </el-form-item>
        </el-form>
      </div>
    </customDialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, toRefs, onMounted, computed } from "vue";
import type { FormInstance } from "element-plus";
import customDialog from "@/components/CustomDialog/index.vue";
import defaultTemplate from "@/components/DefaultRechargeTemlate/defaultTemlate.vue";
import { QuestionFilled } from "@element-plus/icons-vue";
import {
  listForSelector,
  defaultTemplateList,
  getById,
} from "@/api/globalManage/defaultTemplate/index";
import { setProductSave } from "@/api/episodeList/index";
import { appsInfo } from "@/api/globalManage/appletRoute/index";
import { cloneDeep } from "lodash-es";
import { useUserStore } from "@/store/modules/user";

const userStore = useUserStore();
const ruleFormRef = ref<FormInstance>();
const dialogVisible = ref(false);
const form = reactive({
  payTplId: undefined,
  chargeEpisodeNo: undefined,
  unblockCoinAmount: undefined,
  id: 0,
  payTpl: {
    name: "",
    items: [],
  },
});
const formData = reactive(Object.assign({}, form));

const title = ref<string>("");

interface selectType {
  value: number;
  text: string;
  [key: string]: any;
}
const optionEpisode = ref<Array<selectType>>([]);
const baseTemplateRef = ref();
const episodeNumTotal = ref();

// 付费卡点 / 每集价格 规则
const episodeNoRules = (rule: any, value: any, callback: any) => {
  // console.log("value------*** ***-", value, rule);
  let reg = /^[1-9]\d*$/; // 大于0的整数
  if (rule.field === "chargeEpisodeNo") {
    if (!+value || +value < 0) {
      return callback(new Error("请填写大于0的整数"));
    } else if (!reg.test(value) || +value > episodeNumTotal.value) {
      return callback(
        new Error(`请输入剧集${episodeNumTotal.value}之内的集数`)
      );
    } else {
      callback();
    }
  } else if (rule.field === "unblockCoinAmount") {
    if (!+value || !reg.test(value)) {
      return callback(new Error(`请输入大于0的整数`));
    } else if (+value < 10) {
      return callback(new Error("每集需要消耗的追剧币不能低10"));
    } else if (+value > 1000) {
      return callback(new Error(`每集需要消耗的追剧币不能高于1000`));
    } else {
      callback();
    }
  }
};

const rules = reactive({
  chargeEpisodeNo: [
    { required: true, validator: episodeNoRules, trigger: "blur" },
  ],
  unblockCoinAmount: [
    { required: true, validator: episodeNoRules, trigger: "blur" },
  ],
});

// 关闭
const closeDialog = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl?.resetFields();
  dialogVisible.value = false;
};

// 保存配置
const emit = defineEmits(["success"]);
const confirmDialog = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate(async (valid) => {
    if (valid) {
      let temp = await confirmTemp();
      formData.payTpl = temp;
      setProductSave(formData).then(() => {
        ElMessage.success("设置成功");
        emit("success");
        dialogVisible.value = false;
      });
    }
  });
};

// 修改充值模板
const confirmTemp = () => {
  let params = {
    // id: formData?.payTplId,
    name:
      optionEpisode.value.find(
        (x: Record<string, any>) => x.value === formData?.payTplId
      )?.text || "",
    items: baseTemplateRef.value.relationDtoList,
  };
  return params;
};

// 切换模板
const changeTemplate = (val: number | string) => {
  getById(val).then((res: Record<string, any>) => {
    nextTick(() => {
      baseTemplateRef.value.relationDtoList = cloneDeep(res?.items);
    });
  });
};

// 获取默认模板
const getDefaultTemplate = () => {
  defaultTemplateList({ entryType: 0 }).then((res: Record<string, any>) => {
    if (res.code) {
      nextTick(() => {
        baseTemplateRef.value.relationDtoList = JSON.parse(
          JSON.stringify(res.data?.productDtoList)
        );
      });
    }
  });
};

// 获取小程序信息
const getAppsInfo = (data: number) => {
  appsInfo(data).then((res: Record<string, any>) => {
    formData.payTplId = res?.payTplId;
    if (!res?.payTplId) {
      return ElMessage.warning("抱歉，该小程序没有默认充值模板");
    }
    changeTemplate(res?.payTplId);
  });
};

// 获取充值模板list
const getTemplateList = () => {
  listForSelector({}).then((res: any) => {
    optionEpisode.value = res || [];
  });
};

// 父级电子显示dialog
const showDialog = (val: any) => {
  // console.log("信息----", val);
  dialogVisible.value = true;
  title.value = `收费设置-${val?.name}`;
  formData.chargeEpisodeNo = val?.chargeEpisodeNo || undefined;
  formData.unblockCoinAmount = val?.unblockCoinAmount || undefined;
  episodeNumTotal.value = val?.episodeNum || undefined;
  formData.id = val?.id || 0;
  formData.payTplId = undefined;
  // 模板id没有值 通过小程序id 获取默认模板，有值直接获取
  let userAppid = +userStore.user.userAppid;
  if (!val?.payTplId) {
    getAppsInfo(userAppid);
  } else {
    changeTemplate(val?.payTplId);
  }
  getTemplateList();
};

defineExpose({
  showDialog,
});
</script>

<style scoped lang="scss">
.form_box {
  padding: 0 20px;

  .item_episodeNo {
    :deep(.el-form-item__content) {
      flex-wrap: nowrap;
    }
  }
}

.template_box {
  :deep(.el-form-item) {
    margin-bottom: 18px;
  }
}
</style>
